package com.lihepeng.leecode.mulitithread.semaphore;

/**
 * 线程互斥案例
 */
public class MutexDemo {
    private static int mute =1;

    public static void main(String[] args) {
        innnerClass innnerClass = new innnerClass();
        innnerClass.setName("线程1");
        innnerClass innnerClass1 = new innnerClass();
        innnerClass1.setName("线程2");
        Thread t1 = new Thread(innnerClass);
        Thread t2 = new Thread(innnerClass1);
        t1.start();
        t2.start();


    }
    static class innnerClass implements Runnable{
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            while (true) {
                // wait
                if (mute>=0) {
                    mute--;
                    //  临界区代码
                    try {
                        System.out.println(this.getName()+"已经进入临界区代码");
                        Thread.sleep(1000);
                        mute++;
                        System.out.println(this.getName()+"完成操作释放代码");
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else {
                    // singal
                    try {
                        System.out.println("已经有线程进入临界区"+this.getName());
                        Thread.sleep(100);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    //时间片流转
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }
    }
}
